package cz.muni.fi.pa165.library.backend;

import cz.muni.fi.pa165.library.api.BookTO;
import cz.muni.fi.pa165.library.api.BorrowService;
import cz.muni.fi.pa165.library.api.BorrowTO;
import cz.muni.fi.pa165.library.api.ReaderTO;
import java.util.Date;
import java.util.List;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Filip Ligac
 */
@Service
@Transactional
public class BorrowServiceImpl implements BorrowService {

    private BorrowDAO borrowDAO;

    public void setBorrowDAO(BorrowDAO borrowDAO) {
        this.borrowDAO = borrowDAO;
    }

    @Secured("ROLE_LIBRARIAN")
    public BorrowTO createBorrow(BorrowTO borrowTO) {
        return DTOConvertor.convertBorrowEntityToTO(borrowDAO.createBorrow(DTOConvertor.convertBorrowTOToEntity(borrowTO)));
    }

    @Secured("ROLE_LIBRARIAN")
    public List<BorrowTO> findAllBorrows() {
        return DTOConvertor.convertBorrowEntityListToTOList(borrowDAO.findAllBorrows());
    }

    @Secured("ROLE_LIBRARIAN")
    public BorrowTO findBorrowByID(Long borrowID) {
        return DTOConvertor.convertBorrowEntityToTO(borrowDAO.findBorrowById(borrowID));
    }

    @Secured("ROLE_LIBRARIAN")
    public List<BorrowTO> findBorrowsByReader(ReaderTO readerTO) {
        return DTOConvertor.convertBorrowEntityListToTOList(borrowDAO.findBorrowsByReader(DTOConvertor.convertReaderTOToEntity(readerTO)));
    }

    @Secured("ROLE_LIBRARIAN")
    public BorrowTO findBorrowByTitle(BookTO titleTO) {
        return DTOConvertor.convertBorrowEntityToTO(borrowDAO.findBorrowByTitle(DTOConvertor.convertBookTOToEntity(titleTO)));
    }

    @Secured("ROLE_LIBRARIAN")
    public void updateExpirationDate(BorrowTO borrowTO, Date newExpirationDate) {
        borrowDAO.updateExpirationDate(DTOConvertor.convertBorrowTOToEntity(borrowTO), newExpirationDate);
    }

    @Secured("ROLE_LIBRARIAN")
    public BorrowTO returnBooks(BorrowTO borrowTO, List<BookTO> titlesTO) {
        return DTOConvertor.convertBorrowEntityToTO(borrowDAO.returnBooks(DTOConvertor.convertBorrowTOToEntity(borrowTO),
                DTOConvertor.convertBookTOListToEntityList(titlesTO)));
    }

    @Secured("ROLE_LIBRARIAN")
    public void borrowBooks(BorrowTO borrowTO, List<BookTO> titlesTO) {
        borrowDAO.borrowBooks(DTOConvertor.convertBorrowTOToEntity(borrowTO), DTOConvertor.convertBookTOListToEntityList(titlesTO));
    }

    @Secured("ROLE_LIBRARIAN")
    public boolean deleteBorrow(BorrowTO borrowTO) {
        return borrowDAO.deleteBorrow(DTOConvertor.convertBorrowTOToEntity(borrowTO));
    }
}
